package com.example.finger.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.SerialPortUtil;
import com.example.finger.adpter.TaskAdapter;
import com.example.finger.bean.LockLog;
import com.example.finger.bean.TaskSheet;
import com.example.finger.dialog.OpenTempLockDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyxmaster.lib.circledialog.CircleDialog;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.util.DateUtils;
import com.lyxmaster.lib.util.SharedPreferencesHelper;
import com.lyxmaster.lib.xutils.ex.DbException;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LYX on 2018/11/23.
 */

public class TemporaryTaskFragment extends MyBaseFragment {
    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_temporary, container, false);

        listView = rootView.findViewById(R.id.listview);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TaskSheet taskSheet = FingerHelper.getInStance().taskSheetTempList.get(i);

                long dateNow = new Date().getTime();
                long dataStart = DataConfig.strToDateLong(taskSheet.getTask().getTimestart()).getTime();
                long dataEnd = DataConfig.strToDateLong(taskSheet.getTask().getTimeend()).getTime();

                if(dateNow >= dataStart && dateNow <= dataEnd) {
//                    openLock(taskSheet);

                    OpenTempLockDialog openTempLockDialog = OpenTempLockDialog.getInstance(new Gson().toJson(taskSheet));
                    openTempLockDialog.show(((FragmentActivity)(getContext())).getSupportFragmentManager(), "opentemp");
                }else {
                    Toasty.error(getContext(), "任务单不在有效时间内").show();
                }
            }
        });

        return  rootView;
    }

    private void openLock(final TaskSheet taskSheet){
        final LockLog lockLog = new LockLog();
        lockLog.tasknum = taskSheet.getTask().getNumber();
        lockLog.keynum = DataConfig.getImei(getContext());
        lockLog.time = DataConfig.getStringDate();
        lockLog.operator1 = taskSheet.getTask().getOp1();
        lockLog.operator2 = taskSheet.getTask().getOp2();
        lockLog.locknum = taskSheet.getTask().getLocknum().split(" ")[0];
        lockLog.state = "关";
        new CircleDialog.Builder(getActivity())
                .setCanceledOnTouchOutside(true)
                .setCancelable(true)
                .setTitle("锁操作")
                .setText("请选择操作")
                .setNegative("取消", null)
                .setNeutral("解封", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            FingerHelper.getInStance().dbManager.save(lockLog);
                            Toasty.success(getContext(), "操作成功").show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toasty.error(getContext(), "操作失败" + e.getMessage()).show();
                        }
                    }
                })
                .setPositive("施封", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            FingerHelper.getInStance().dbManager.save(lockLog);
                            Toasty.success(getContext(), "操作成功").show();
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toasty.error(getContext(), "操作失败" + e.getMessage()).show();
                        }


                    }
                }).show();
    }

    private String getSendData(String order,String lockNum){
        String id = DataConfig.hexByteToHexString(lockNum.getBytes(Charset.forName("US-ASCII")));
        String s = 19 + order + id + "112233112233" + DateUtils.getStringDate("yyMMddHHmmss") + "0000" + DataConfig.hexByteToHexString("RT000001".getBytes(Charset.forName("US-ASCII")));
        byte[] data = DataConfig.hexStringToHexBytes(s);
        data[0] = (byte)(data.length + 1);
        byte[] crc = DataConfig.CRC_16(data, data.length, 0x6290);
        return "FE" + DataConfig.hexByteToHexString(data) + DataConfig.hexByteToHexString(crc) + "FF";
    }

    public void onResume(){
        super.onResume();

        FingerHelper.getInStance().taskSheetTempList = new Gson().fromJson((String)(new SharedPreferencesHelper().getSharedPreference(getContext(), FingerHelper.TMEMPTASK, "[]")), new TypeToken<List<TaskSheet>>(){}.getType());
        if( FingerHelper.getInStance().taskSheetTempList == null) FingerHelper.getInStance().taskSheetTempList = new ArrayList<>();
        listView.setAdapter(new TaskAdapter(FingerHelper.getInStance().taskSheetTempList,getContext()));
    }
}
